<template>
  <div class="flight-list">
    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="hover">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="航班名称">
          <el-input 
            v-model="searchForm.flightName" 
            placeholder="请输入航班名称" 
            prefix-icon="el-icon-search"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="起飞时间">
          <el-date-picker
            v-model="searchForm.startTime"
            type="date"
            placeholder="选择起飞日期"
            value-format="yyyy-MM-dd"
            :picker-options="{
              disabledDate(time) {
                return time.getTime() < Date.now() - 8.64e7
              }
            }"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="航班状态">
          <el-select v-model="searchForm.fstatus" placeholder="选择状态" clearable>
            <el-option :label="'可预订'" :value="1">
              <i class="el-icon-circle-check status-icon success"></i> 可预订
            </el-option>
            <el-option :label="'已起飞'" :value="0">
              <i class="el-icon-video-play status-icon warning"></i> 已起飞
            </el-option>
            <el-option :label="'已停航'" :value="-1">
              <i class="el-icon-circle-close status-icon danger"></i> 已停航
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
            <el-button @click="resetSearch" icon="el-icon-refresh">重置</el-button>
          </el-button-group>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="hover">
      <div class="operation-bar">
        <div class="left">
          <el-button type="primary" @click="handleAdd" icon="el-icon-plus">新增航班</el-button>
          <el-button-group v-if="selectedFlights.length">
            <el-button 
              type="danger" 
              @click="handleBatchStatusChange(-1)"
              icon="el-icon-download"
            >批量停航</el-button>
            <el-button 
              type="success" 
              @click="handleBatchStatusChange(1)"
              icon="el-icon-upload2"
            >批量发布</el-button>
          </el-button-group>
        </div>
        <div class="right">
          <el-button type="text" @click="fetchData" icon="el-icon-refresh">刷新数据</el-button>
        </div>
      </div>

      <el-table
        :data="paginatedData"
        border
        stripe
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" fixed="left"></el-table-column>
        <el-table-column label="航班信息" min-width="280" fixed="left">
          <template v-slot="{ row }">
            <div class="flight-info">
              <div class="flight-name">{{ row.fname }}</div>
              <div class="flight-route">
                <span class="city">{{ row.ffrom }}</span>
                <i class="el-icon-right route-icon"></i>
                <span class="city">{{ row.fto }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="航班时间" width="340">
          <template v-slot="{ row }">
            <div class="time-info">
              <div class="time-item">
                <i class="el-icon-time"></i>
                <span class="label">起飞：</span>
                <span class="time">{{ formatDateTime(row.fstart) }}</span>
              </div>
              <div class="time-item">
                <i class="el-icon-time"></i>
                <span class="label">到达：</span>
                <span class="time">{{ formatDateTime(row.fend) }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="finfo" label="航班信息" min-width="200">
          <template v-slot="{ row }">
            <el-tooltip :content="row.finfo" placement="top">
              <div class="info-cell">{{ row.finfo }}</div>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="票价" width="120" align="right">
          <template v-slot="{ row }">
            <span class="price">¥{{ formatPrice(row.frent) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100" align="center">
          <template v-slot="{ row }">
            <el-tag :type="getStatusType(row.fStatus)" effect="dark">
              {{ getStatusText(row.fStatus) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right">
          <template v-slot="{ row }">
            <el-button-group>
              <el-button
                :type="row.fStatus === 1 ? 'warning' : 'success'"
                size="mini"
                @click="handleStatusChange(row)"
                :disabled="row.fStatus === 0"
              >
                {{ row.fStatus === 1 ? '停航' : '预订' }}
              </el-button>
              <el-button
                type="primary"
                size="mini"
                @click="handleEdit(row)"
                icon="el-icon-edit"
              >
                编辑
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalData"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <flight-add
      :visible.sync="addDialogVisible"
      :flight="currentFlight"
      @success="handleAddSuccess"
    />
  </div>
</template>

<script>
import FlightAdd from './FlightAdd.vue'
import request from '@/utils/request'

export default {
  name: 'FlightList',
  
  components: {
    FlightAdd
  },

  data() {
    return {
      // 搜索表单
      searchForm: {
        flightName: '',
        fstatus: '',
        startTime: ''
      },
      // 表格数据
      tableData: [],
      loading: false,
      selectedFlights: [],
      // 新增对话框
      addDialogVisible: false,
      // 当前编辑的航班
      currentFlight: null,
      // 分页
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    }
  },

  created() {
    this.fetchData()
  },

  computed: {
    // 计算分页后的数据
    paginatedData() {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      return this.filteredData.slice(start, end)
    },

    // 计算筛选后的数据
    filteredData() {
      let result = [...this.tableData]
      
      // 根据航班名筛选
      if (this.searchForm.flightName) {
        const keyword = this.searchForm.flightName.toLowerCase()
        result = result.filter(item => 
          item.fname.toLowerCase().includes(keyword)
        )
      }
      
      // 根据状态筛选
      if (this.searchForm.fstatus !== '') {
        result = result.filter(item => 
          item.fStatus === this.searchForm.fstatus
        )
      }

      // 添加起飞时间筛选
      if (this.searchForm.startTime) {
        const searchDate = new Date(this.searchForm.startTime)
        result = result.filter(item => {
          if (!item.fstart) return false
          const flightDate = new Date(item.fstart)
          return (
            flightDate.getFullYear() === searchDate.getFullYear() &&
            flightDate.getMonth() === searchDate.getMonth() &&
            flightDate.getDate() === searchDate.getDate()
          )
        })
      }
      
      return result
    },

    // 计算总数据量
    totalData() {
      return this.filteredData.length
    }
  },

  methods: {
    // 获取航班列表
    async fetchData() {
      this.loading = true
      try {
        const res = await request.get('/flight/list')
        if (res.code === 0) {
          this.tableData = res.data
        } else {
          this.$message.error(res.msg || '获取航班列表失败')
        }
      } catch (error) {
        console.error('获取航班列表失败:', error)
        this.$message.error('获取航班列表失败')
      }
      this.loading = false
    },

    // 获取状态类型
    getStatusType(status) {
      switch (Number(status)) {
        case 1:
          return 'success'
        case 0:
          return 'warning'
        case -1:
          return 'danger'
        default:
          return 'info'
      }
    },

    // 获取状态文本
    getStatusText(status) {
      switch (Number(status)) {
        case 1:
          return '可预订'
        case 0:
          return '已起飞'
        case -1:
          return '已停航'
        default:
          return '未知'
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1 // 重置到第一页
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        flightName: '',
        fstatus: '',
        startTime: ''
      }
      this.pagination.currentPage = 1 // 重置到第一页
    },

    // 表格选择
    handleSelectionChange(selection) {
      this.selectedFlights = selection
    },

    // 新增航班
    handleAdd() {
      this.currentFlight = null
      this.addDialogVisible = true
    },

    // 新增成功回调
    handleAddSuccess() {
      this.$message.success('添加成功')
      this.fetchData()
    },

    // 编辑航班
    async handleEdit(row) {
      this.currentFlight = { ...row }
      this.addDialogVisible = true
    },

    // 更改单个航班状态
    async handleStatusChange(row) {
      const newStatus = row.fStatus === 1 ? -1 : 1
      const actionText = newStatus === 1 ? '起飞' : '停航'
      
      try {
        await this.$confirm(`确认要${actionText}该航班吗？`, '提示', {
          type: 'warning'
        })
        
        const res = await request.get('/FlightStatusServlet', {
          params: {
            fid: row.fid,
            fstatus: newStatus
          }
        })
        
        if (res.code === "0") {
          row.fstatus = newStatus
          this.fetchData()
          this.$message.success(`${actionText}成功`)
        } else {
          this.$message.error(res.msg || `${actionText}失败`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error(`${actionText}失败:`, error);
          this.$message.error(`${actionText}失败`);
        }
      }
    },

    // 批量更改状态
    async handleBatchStatusChange(status) {
      if (!this.selectedFlights.length) return
      
      const actionText = status === 1 ? '上架' : '下架'
      
      try {
        await this.$confirm(`确认要批量${actionText}选中的航班吗？`, '提示', {
          type: 'warning'
        })
        
        const fids = this.selectedFlights.map(flight => flight.fid).join(',')
        const res = await request.get('/FlightChangeSelectServlet', {
          params: {
            fids,
            fstatus: status
          }
        })
        
        if (res.code === '0') {
          this.$message.success(`批量${actionText}成功`)
          this.fetchData()
        } else {
          this.$message.error(res.msg || `批量${actionText}失败`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error(`批量${actionText}失败:`, error)
          this.$message.error(`批量${actionText}失败`)
        }
      }
    },

    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1 // 重置到第一页
    },
    
    // 处理页码变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val
    },

    // 添加时间格式化方法
    formatDateTime(datetime) {
      if (!datetime) return '未设置';
      const date = new Date(datetime);
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${month}-${day} ${hours}:${minutes}`;
    },

    // 格式化价格
    formatPrice(price) {
      return Number(price).toFixed(2);
    },

    // 格式化日期显示
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  }
}
</script>

<style lang="less" scoped>
.flight-list {
  padding: 20px;
  background-color: #f5f7fa;

  .search-card {
    margin-bottom: 20px;
    
    .search-form {
      .el-form-item {
        margin-bottom: 0;
        margin-right: 20px;

        // 调整日期选择器宽度
        .el-date-picker {
          width: 180px;
        }
      }
    }
  }

  .table-card {
    .operation-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }

    .flight-info {
      .flight-name {
        font-weight: bold;
        color: #303133;
        margin-bottom: 8px;
      }

      .flight-route {
        display: flex;
        align-items: center;
        color: #606266;

        .city {
          font-size: 14px;
        }

        .route-icon {
          margin: 0 8px;
          color: #409EFF;
        }
      }
    }

    .time-info {
      .time-item {
        display: flex;
        align-items: center;
        margin: 4px 0;

        .el-icon-time {
          color: #909399;
          margin-right: 4px;
        }

        .label {
          color: #909399;
          margin-right: 4px;
        }

        .time {
          color: #303133;
          font-weight: 500;
        }
      }
    }

    .info-cell {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .price {
      color: #f56c6c;
      font-weight: bold;
    }
  }

  .status-icon {
    margin-right: 5px;
    
    &.success {
      color: #67c23a;
    }
    
    &.warning {
      color: #e6a23c;
    }
    
    &.danger {
      color: #f56c6c;
    }
  }

  .pagination-container {
    text-align: right;
    padding-top: 20px;
  }
}

// 响应式优化
@media screen and (max-width: 1400px) {
  .flight-list {
    .search-form {
      .el-form-item {
        margin-bottom: 10px;
      }
    }
  }
}
</style> 